//
//  ReloadWeatherData.m
//  FastDoctor
//
//  Created by 李通 on 16/7/6.
//  Copyright © 2016年 sc. All rights reserved.
//

#import "ReloadWeatherData.h"

@implementation ReloadWeatherData

+ (void)initNetworkDataWithString:(NSString *)cityStr {
    
    
    //判断定位信息是否正常
    if ([cityStr isEqualToString:@"数据为空"] || [cityStr isEqualToString:@"数据没有地点信息"])
    {
        
        NSDictionary *dict = @{};
        
        //使用通知传递错误数据
        NSNotification *notification = [NSNotification notificationWithName:@"network" object:nil userInfo:@{@"weather":dict,@"city":@"GPS定位失败"}];
        
        [[NSNotificationCenter defaultCenter]postNotification:notification];
        
        [SVProgressHUD dismiss];
        
        return;
    }
    
    
    NSString *url = @"http://api.map.baidu.com/telematics/v3/weather";
    
    NSDictionary *paramDic = @{@"location":cityStr,
                               @"output":@"json",
                               @"ak":@"17IvzuqmKrK1cGwNL6VQebF9"
                               };
    
    [[NetWorkTool sharedWorkTool]GET:url parameters:paramDic success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        NSArray *array = responseObject[@"results"];
        
        //如果没有获取到数据则提示错误,直接返回
        if (array == nil) {
            
            [SVProgressHUD showErrorWithStatus:@"网络请求错误,请重试"];
            return ;
        }
         //将获取到的数据进行包装
        __block NSString *string;
        __block NSDictionary *dict;
        
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            dict = [obj[@"weather_data"] firstObject];
            string = obj[@"currentCity"];
        }];
         //使用通知传递获取到的网络数据
        NSNotification *notification = [NSNotification notificationWithName:@"network" object:nil userInfo:@{@"weather":dict,@"city":string}];
        
        [[NSNotificationCenter defaultCenter]postNotification:notification];
        
        [SVProgressHUD dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

@end
